"""
 Module: cfginit.py
 Ver 0.9.0

 Rev 0.9.2; Last: 03/11/2013 - Previous: 03/11/2013 (AEM)
   - Incorporate Plot DMM modules

 Rev 0.9.3-0; Last: 03/20/2013 - Previous: 03/20/2013 (AEM)
   - Mods to accommodate GUI (module readermain.py)
     Either execution mode is transparent to this module.

 Support initialization functions for readmeter.py

 This file is part of the DMM Reader project.

 Copyright (C) 2012-2013  Arnold E. Morgan

    DMM Reader is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

# *** System Supplied Modules ***
import sys
import os
import datetime

# *** Config file is assumed to be in the same
#     directory as readmeter.py.
CfgFileName = "readmeter.cfg"

# ********** Function Definitions **********

def GetCfgSettings(IsTerminal):
   """ Read in serial port config settings.
       Config file MUST be named 'readmeter.cfg'.
       Return values back to caller as a two value tuple
         1 - rtn state: False = fail, True = success
         2 - cfg data as a dictionary
   """

   RtnValue = (False, '', '')     # *** Assume fail return state as default ***
   RtnMssg = ''
   ConfigValues = {}
   
   if IsTerminal:
      print "Ready to open and read config file..."
   try:
      for line in open(CfgFileName, 'r'):
         TempStr = line.strip()
         if len(TempStr) > 0 and TempStr[0] != "#" and TempStr.find('=') != -1:
            (theKey, theValue) = TempStr.split("=")
            ConfigValues[theKey.strip()] = theValue.strip()      

      RtnValue = (True, ConfigValues, '')
      
   except IOError, (errno, strerror):
      RtnMssg = "File open error(%s): %s" % (errno, strerror)
      RtnValue = (False, ConfigValues, RtnMssg)
   except:
      RtnMssg = "Unexpected error: ", sys.exc_info()[0]
      RtnValue = (False, ConfigValues, RtnMssg)
   finally: 
      RtnMssg = "Config file settings read complete"
      RtnValue = (True, ConfigValues, RtnMssg)

   return RtnValue
# *************** End of fcn GetCfgSettings ************

def CreateLogFile(LogFileName, IsTerminal):
   """ Create the log file.
       If log file name already exists, rename it
       before creating a new version.
       Return values to caller as a two value tuple
         1 - rtn state: False = fail, True = success
         2 - handle to log file if open successful
   """

   OldLogName = ""        # *** Rename LogFileName if it exists ***
   filebasename = ""      # *** Need to separate basename and 
   fileext = ""           #     extension for renaming 
   RtnValue = (True, '')  # *** Assume success return state as default ***
   LogFailFlag = False

   if len(LogFileName) > 0: 
      # *** Save any existing log file with the default name
      #     before creating a new log file.
      if os.path.exists(LogFileName):
         now = datetime.datetime.now()
         # *** Separate the filename and ext ***
         (filebasename, fileext) = os.path.splitext(LogFileName)
         
         # *** Build a new name by adding date and time values to the name *** 
         OldLogName = filebasename + "_" + now.strftime("%Y%m%d_%H%M") + fileext
         if IsTerminal:
            print "Old Log Name: %s" % OldLogName
         try:
            os.rename(LogFileName, OldLogName)
         except OSError, mssg:
            if IsTerminal:
               print "Cannot rename file %s; skipping temperature logging: %s" % (LogFileName, mssg)
            LogFailFlag = True
      # -----------------------------------------------------------------------
      # *** If rename failed there is nothing else to do ***
      if not LogFailFlag:
         try:
            # *** Open the file for write; return the file handle of open success ***
            fout = open(LogFileName, "w")
            return (True, fout)
         except IOError, mssg:
            if IsTerminal:
               print "Cannot create file %s; skipping logging operation: %s" % (LogFileName, mssg)
      # -----------------------------------------------------------------------

   return RtnValue
# ************** End of fcn CreateLogFile *******************
